package com.hmkj.web.controller.index;

import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.core.constant.ConfigNID;
import com.hmkj.core.eolinker.models.ModelRealTime;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.index.EquityRecommendModel;
import com.hmkj.core.model.index.RuleModel;
import com.hmkj.core.po.banner.Banner;
import com.hmkj.core.po.index.EquityRecommend;
import com.hmkj.core.po.trader.Trader;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.banner.BannerService;
import com.hmkj.core.service.index.EquityRecommendService;
import com.hmkj.core.service.strategy.StrategyRankService;
import com.hmkj.core.service.trader.TraderService;
import com.hmkj.web.controller.GenericController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(description = "首页相关")
@Slf4j
@RestController
@RequestMapping(GenericController.BASE_API_URL)
public class AppIndexController extends GenericController<Integer, User> {

    @Resource
    BannerService bannerService;
    @Resource
    EquityRecommendService equityRecommendService;
    @Resource
    StrategyRankService strategyRankService;
    @Resource
    TraderService traderService;

    @ApiOperation(value = "Banner", notes = "Banner")
    @RequestMapping(value = "/banner", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity bannerPc(@ApiParam("PC/APP,1PC,2APP") @RequestParam Integer type) throws Exception {
        log.info("获取banner列表");
        if (null == type || (type != Banner.ISPC.T1.code && type != Banner.ISPC.T2.code)) {
            throw new BussinessException("参数有误");
        }
        List<Banner> bannerList = bannerService.findBannerList(type);
        return ok(bannerList);
    }

    @ApiOperation(value = "操盘达人", notes = "操盘达人")
    @RequestMapping(value = "/expert", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity expert() throws Exception {
        List<Trader> list = traderService.selectExpert();
        for (Trader trader : list) {
            trader.setName(StringUtils.hideRealName(trader.getName()));
        }
        return ok(list);
    }

    @ApiOperation(value = "首页最新动态", notes = "首页最新动态")
    @RequestMapping(value = "/news", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity newsApp() throws Exception {
        return ok();
    }

    @ApiOperation(value = "策略排行", notes = "策略排行")
    @RequestMapping(value = "/ideaRank", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity ideaRank() throws Exception {
        return ok(strategyRankService.selectStrategyRank());
    }

    @ApiOperation(value = "隐藏数据标识", notes = "隐藏数据标识")
    @RequestMapping(value = "/appVersion", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity appHide() throws Exception {
        return ok(m -> {
            m.put("appVersion", redisService.get(ConfigNID.APP_HIDE));
        });
    }

    @ApiOperation(value = "首页每日推荐", notes = "首页每日推荐")
    @RequestMapping(value = "/recommend", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity recommend() throws Exception {
        List<EquityRecommend> list = equityRecommendService.selectRecommend();
        List<EquityRecommendModel> resultList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (EquityRecommend recommend : list) {
                ModelRealTime realTime = stockByCacheOrInte(recommend.getEquityCode());
                EquityRecommendModel model = new EquityRecommendModel();
                BeanUtils.copyProperties(recommend, model);
                if (realTime != null) {
                    model.setStockCode(recommend.getEquityCode());
                    model.setStockName(recommend.getEquityName());
                    model.setRisePre(realTime.getRise_pre());
                    model.setRisePrice(realTime.getRise_price());
                    model.setLastPrice(realTime.getLast_price());
                    resultList.add(model);
                }
            }
        }
        return ok(m -> {
            m.put("list", resultList);
        });
    }


    @ApiOperation(value = "股票推荐列表", notes = "股票推荐列表")
    @ResponseBody
    @RequestMapping(value = "/equityRecommend", method = RequestMethod.POST)
    public ResultEntity equityRecommend() throws Exception {
        Map<String, Object> data = new HashMap<>();
        //点买王
        List<EquityRecommend> recommends = equityRecommendService.select(new EquityRecommend(t -> {
            t.setTopBuy(EquityRecommend.TOPBUY.T1.code);
        }));
        data.put("topBuy", recommends);

        //最近购买
        List<EquityRecommend> recents = equityRecommendService.select(new EquityRecommend(t -> {
            t.setRecentBuy(EquityRecommend.RECENTBUY.T1.code);
        }));
        List<EquityRecommendModel> recentList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(recents)) {
            for (EquityRecommend recent : recents) {
                ModelRealTime realTime = stockByCacheOrInte(recent.getEquityCode());
                EquityRecommendModel model = new EquityRecommendModel();
                BeanUtils.copyProperties(recent, model);
                if (realTime != null) {
                    model.setRisePre(realTime.getRise_pre());
                    model.setRisePrice(realTime.getRise_price());
                    model.setLastPrice(realTime.getLast_price());
                }
                recentList.add(model);
            }
        }
        data.put("recents", recentList);

        //其他人在买
        List<EquityRecommend> others = equityRecommendService.select(new EquityRecommend(t -> {
            t.setOtherBuy(EquityRecommend.OTHERBUY.T1.code);
        }));
        List<EquityRecommendModel> otherList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(others)) {
            for (EquityRecommend other : others) {
                ModelRealTime realTime = stockByCacheOrInte(other.getEquityCode());
                EquityRecommendModel model = new EquityRecommendModel();
                BeanUtils.copyProperties(other, model);
                if (realTime != null) {
                    model.setRisePre(realTime.getRise_pre());
                    model.setRisePrice(realTime.getRise_price());
                    model.setLastPrice(realTime.getLast_price());
                }
                otherList.add(model);
            }
        }
        data.put("others", otherList);

        //猜你想买
        List<EquityRecommend> guessLiskes = equityRecommendService.select(new EquityRecommend(t -> {
            t.setGuessLike(EquityRecommend.GUESSLIKE.T1.code);
        }));
        List<EquityRecommendModel> guessList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(guessLiskes)) {
            for (EquityRecommend guessLike : guessLiskes) {
                ModelRealTime realTime = stockByCacheOrInte(guessLike.getEquityCode());
                EquityRecommendModel model = new EquityRecommendModel();
                BeanUtils.copyProperties(guessLike, model);
                if (realTime != null) {
                    model.setRisePre(realTime.getRise_pre());
                    model.setRisePrice(realTime.getRise_price());
                    model.setLastPrice(realTime.getLast_price());
                }
                guessList.add(model);
            }
        }
        data.put("guessLike", guessList);

        //今日推荐
        List<EquityRecommend> todayRecommends = equityRecommendService.select(new EquityRecommend(t -> {
            t.setOtherBuy(EquityRecommend.TODAYRECOMMEND.T1.code);
        }));
        List<EquityRecommendModel> todayList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(todayRecommends)) {
            for (EquityRecommend today : todayRecommends) {
                ModelRealTime realTime = stockByCacheOrInte(today.getEquityCode());
                EquityRecommendModel model = new EquityRecommendModel();
                BeanUtils.copyProperties(today, model);
                if (realTime != null) {
                    model.setRisePre(realTime.getRise_pre());
                    model.setRisePrice(realTime.getRise_price());
                    model.setLastPrice(realTime.getLast_price());
                }
                todayList.add(model);
            }
        }
        data.put("todayRecommends", todayList);
        return ok(data);

    }

    @ApiOperation(value = "热门股票列表", notes = "热门股票列表")
    @ResponseBody
    @RequestMapping(value = "/hotStock", method = RequestMethod.POST)
    public ResultEntity hotStock() throws Exception {
        //热门股票
        List<EquityRecommend> hots = equityRecommendService.select(new EquityRecommend(t -> {
            t.setStatus(EquityRecommend.STATUS.T1.code);
        }));
        List<EquityRecommendModel> hotList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(hots)) {
            for (EquityRecommend hot : hots) {
                ModelRealTime realTime = stockByCacheOrInte(hot.getEquityCode());
                EquityRecommendModel model = new EquityRecommendModel();
                BeanUtils.copyProperties(hot, model);
                if (realTime != null) {
                    model.setRisePre(realTime.getRise_pre());
                    model.setRisePrice(realTime.getRise_price());
                    model.setLastPrice(realTime.getLast_price());
                }
                hotList.add(model);
            }
        }
        return ok(hotList);
    }

    @ApiOperation(value = "交易规则", notes = "交易规则")
    @ResponseBody
    @RequestMapping(value = "/rules", method = RequestMethod.POST)
    public ResultEntity rule() throws Exception {
        List<RuleModel> ruleModels = new ArrayList<>();
        RuleModel model = new RuleModel();

        model.setName("什么是点买人，什么是投资人");
        model.setContent("点买人是指策略提供人，通过平台发布股票买卖策略，如选择什么股票，买多少股，止盈点是多少，止损点是多少，何时买入，何时卖出；投资人是实际购买股票的自然人或者法人，投资人提供资金，证券账号，自由选择平台上的股票策略，根据实际情况匹配，并严格按照策略要求买卖股票。");
        ruleModels.add(model);

        model = new RuleModel();
        model.setName("什么是点买交易？");
        model.setContent("点买交易是本平台通过点买人发起股票策略（选择股票，选择购买数量，设置止盈止损），平台收集这些策略后转发给所有投资人，投资人根据自己选择是否匹配，如匹配成功，则点买人与投资人生成一个协议，投资人按点买人的策略要求执行买入卖出对于股票操作");
        ruleModels.add(model);

        model = new RuleModel();
        model.setName("点买时间是什么时候？");
        model.setContent("股票交易日的上午09:30-11:30，下午13:00-14:55");
        ruleModels.add(model);

        model = new RuleModel();
        model.setName("持仓时间是多久？");
        model.setContent("默认每天自动递延，递延费从账户余额扣除，若余额不足或者不符合递延条件，策略将由投资人卖出清算。");
        ruleModels.add(model);

        model = new RuleModel();
        model.setName("什么是递延条件？");
        model.setContent("递延条件是，当可操盘资金低于递延条件时，只能点卖不能点买。");
        ruleModels.add(model);

        model = new RuleModel();
        model.setName("什么是止损？");
        model.setContent("止损是该条策略的亏损线，当达到预设的止损点的时候，系统会自动发起卖出指令给投资人。");
        ruleModels.add(model);

        model = new RuleModel();
        model.setName("什么是交易综合费？");
        model.setContent("交易综合费是由点买人每次发起新的策略时平台收取的服务费用，撮合成功收费，撮合失败不收费，费用包含充值提现费，平台居间费，第三方风控劳务费等（数据仅供参考，以实际平台公布为准)");
        ruleModels.add(model);

        model = new RuleModel();
        model.setName("什么是履约保证金？");
        model.setContent("履约保证金是点买人委托平台冻结在三方公司，用于策略亏损时的赔付金额，如盈利，全额返还。如亏损，按实际亏损赔付，且履约保证金为赔付上限，超出亏损部分由投资人自己承担。");
        ruleModels.add(model);

        model = new RuleModel();
        model.setName("停牌股要怎么处理？");
        model.setContent("当T+D期间点买人策略中股票遇到停牌时，点买人可以在T+D结束前继续持有，也可以选择放弃或买断该策略。当T+D时间到期前三个交易日，点买人必须做出选择是放弃本条策略，或者全额买断本条策略，如果放弃策略，扣除策略对应市值的履约保证金，策略中股票归投资人所有，复牌后所有盈利或者亏损与点买人无关；如果点买人选择全额买断策略，点买人按点买成交价补缴相应的金额，复牌后所有盈利或亏损与投资人无关，100%归点买人所有；若T+D到期前三个交易日，点买人不选择递延，也不选择买断，则默认为选择放弃。");
        ruleModels.add(model);

        model = new RuleModel();
        model.setName("盈亏怎么结算？");
        model.setContent("如策略盈利，点买人获得盈利部分的90%，投资人获得盈利部分的10%（具体分成方式以协议或平台公告为准，次数据仅为参考）；如策略亏损，点买按实际亏损情况将履约保证金为赔付上限。如有超额亏损，由投资人自己承担？例：盈利1000元，点买人获利1000*90%=900元，投资人获利100元。");
        ruleModels.add(model);

        model = new RuleModel();
        model.setName("点买，点卖时出现部分成交后怎么结算？");
        model.setContent("点买时因行情波动原因，无法全部按策略的数量买入时，以实际买入数量为准；点卖时因行情波动原因，无法全部卖出，需等到全部卖出后方可清算。");
        ruleModels.add(model);

        return ok(ruleModels);
    }

//    @ApiOperation(value = "审核版本开关", notes = "审核版本开关")
//    @RequestMapping(value = "isAudit", method = RequestMethod.POST)
//    public ResultEntity isAudit() throws Exception {
//        log.info("审核版本开关");
//        return ok(m -> m.put("isAudit", redisService.get(ConfigNID.IOS_ISAUDIT, Boolean.class)));
//    }


//    @ApiOperation(value = "APP信息", notes = "APP信息")
//    @RequestMapping(value = "appinfo", method = RequestMethod.GET)
//    public ResultEntity appinfo() throws Exception {
//        log.info("审核版本开关");
//        return ok(m -> {
//            m.put("nativeflag","true");
//            m.put("url","http://qhyy.91dacheng.com?app=1");
//        });
//    }
}
